
const userService = require('../service/user.service')
const md5password = require('../utils/password-handle')
const errorTypes = require('../contants/error-types')

// 验证用户注册
const verifyUser = async (ctx, next) => {
  const {username, password} = ctx.request.body
  //验证格式是否正确
  if(!username || !password) {
    return ctx.app.emit('error', error, ctx)
  }
  // 验证用户是否注册
  const result = await userService.getUserByName(username)
  if(result.length) {
    const error = new Error(errorTypes.USER_ALREADY_EXISTS)
    return ctx.app.emit('error', error, ctx)
  }
  
  await next();
}

// 验证登陆
const verifyLogin = async (ctx, next) => {
  // 获取用户信息
  const {username, password} = ctx.request.body
  // 检测输入数据
  if(!username || !password) {
    const error = new Error(errorTypes.NAME_OR_PASSWORD_IS_REQUIRED)
    return ctx.app.emit('error', error, ctx)
  }

  // 从数据库获取用户信息
  const result = await userService.getUserByName(username)
  const user = result[0]
  // 判断是否存在用户
  if(!user) {
    const error = new Error(errorTypes.USER_DOES_NOT_EXISTS)
    return ctx.app.emit('error', error, ctx)
  }
  // 判断密码是否正确
  if(md5password(password) !== user.password) {
    const error = new Error(errorTypes.PASSWORD_IS_INCORRENT)
    return ctx.app.emit('error', error, ctx)
  }

  ctx.user = user
  await next()
}

// 加密密码
const handlePassword = async (ctx, next) => {
  const {password} = ctx.request.body
  ctx.request.body.password = md5password(password)
  
  await next();
}

module.exports = {
  verifyUser,
  handlePassword,
  verifyLogin
}